package com.airticketbooking.task;

import com.airticketbooking.common.constant.StatusConstant;
import com.airticketbooking.mapper.*;
import com.airticketbooking.po.Order;
import com.airticketbooking.po.Ticket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@RequiredArgsConstructor
@Component
@Slf4j
public class OrderTask {

	private final OrderWithTicketMapper orderWithTicketMapper;
	private final OrderMapper orderMapper;
	private final TicketMapper ticketMapper;

	// 每分钟触发一次处理订单内票据状态变化的任务
	@Scheduled(cron = "0 * * * * *")
	public void processTicketsStatusChange() {
		List<Order> orders = orderMapper.getAll();

		for (Order order : orders) {
			// 获取订单下所有票据的ID
			List<Integer> ticketIds = orderWithTicketMapper.getTicketIdsByOrderId(order.getOrderId());

			// 判断订单下的票据是否全部已完成
			if (areAllTicketsFinished(ticketIds)) {
				// 更新订单状态为已完成
				if(order.getStatus() != StatusConstant.ORDER_FINISHED){
					updateOrderStatusToFinished(order);
				}
			}
		}
	}

	// 检查所有票据是否都已完成
	private boolean areAllTicketsFinished(List<Integer> ticketIds) {
		for (Integer ticketId : ticketIds) {
			Ticket ticket = ticketMapper.getTicketById(ticketId);
			// 如果有未完成的票据，返回false
			if (ticket.getStatus() != StatusConstant.TICKET_FINISHED) {
				return false;
			}
		}
		// 所有票据都已完成
		return true;
	}

	// 更新订单状态为已完成
	private void updateOrderStatusToFinished(Order order) {
		order.setStatus(StatusConstant.ORDER_FINISHED);
		order.setUpadateDateTime(LocalDateTime.now());
		orderMapper.modifyOrder(order);
	}
}
